package com.liuyang.concurrency.chapter10;

import java.util.Optional;
import java.util.concurrent.TimeoutException;
import java.util.stream.Stream;

public class Test {
    public static void main(String[] args) throws InterruptedException {
        final Lock lock = new BooleanLock();
        Stream.of("T1", "T2", "T3", "T4")
                .forEach(name -> new Thread(() -> {
                    try {
                        lock.lock(10L);
                        Optional.of(Thread.currentThread().getName() + " have the lock Monitor")
                                .ifPresent(System.out::println);
                        work();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } catch (TimeoutException e) {
                        System.out.println(Thread.currentThread().getName() + "Time out ");
                    } finally {
                        lock.unlock();
                    }

                }, name).start());
    }

    private static void work() throws InterruptedException {
        Optional.of(Thread.currentThread().getName() + "is Working .....").ifPresent(System.out::println);
        Thread.sleep(4_000);
    }
}
